/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */

import fs from 'fs';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { ErrorUrl } from '../../utils/error-url.js';
import { OhosPackageJson } from '../../utils/dependency-util.js';
import { CommonConst } from '../../const/common-const.js';
import path from 'path';

const log = OhosLogger.getLogger('ohos-legacy-dependency-manager-helper');
const solution =
  'The OpenHarmony npm package or module is not compatible with the current model. ' +
  'Use a compatible OpenHarmony npm package or module. ' +
  `For details about the stage and FA models, see ${ErrorUrl.ERROR_URL.modelDiff}.`;

/**
 * 为FA模型支持管理har的依赖
 */
export class LegacyDependencyManagerHelper {
  private readonly _moduleName: string;

  constructor(moduleName: string) {
    this._moduleName = moduleName;
  }

  /**
   * 过config.json/module.json5判断当前模块是否与FA模型兼容
   * @param pkgPath 当前模块的路径
   * @param devPkgJsonObj
   */
  public checkHspOrHarStatusForFAByProfile(pkgPath: string, devPkgJsonObj: OhosPackageJson): boolean {
    const module5File: string = path.resolve(pkgPath, 'src', 'main', CommonConst.MODULE_JSON5);
    const moduleFile: string = path.resolve(pkgPath, 'src', 'main', CommonConst.MODULE_JSON);

    return this.checkHspOrHarStatusForFA(module5File, devPkgJsonObj) || this.checkHspOrHarStatusForFA(moduleFile, devPkgJsonObj);
  }

  /**
   * 判断依赖的包与本FA模块是否兼容, 需要传入module.json或module.json5路径
   * @param runtimeJson 传入module.json或module.json5路径
   * @param devPkgJsonObj
   */
  checkHspOrHarStatusForFA(runtimeJson: string, devPkgJsonObj: OhosPackageJson): boolean {
    // seg结论支持hypium白名单
    if (devPkgJsonObj?.name == CommonConst.HYPIUM_PACKAGE_NAME) {
      return true;
    }
    // 非FA的har或hsp 不支持在FA上运行
    if (fs.existsSync(runtimeJson)) {
      log.printErrorExit(
        'FA_RELY_OH_STAGE',
        [this._moduleName, runtimeJson],
        [[solution]]
      )
    }
    return true;
  }
}
